package top.lrshuai.websocket.ws.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.lrshuai.websocket.user.service.IUserService;
import top.lrshuai.websocket.ws.utils.ChannelGroupUtil;

@Slf4j
@Component
public class BaseChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private ChannelGroupUtil channelGroupUtil=ChannelGroupUtil.getInstance();

    @Autowired
    private IUserService userService;

    /**
     * 连接开启
     * @param channelHandlerContext
     */
    @Override
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) {
        channelGroupUtil.addChannel(channelHandlerContext.channel());
        channelGroupUtil.userRegister(channelHandlerContext.channel(),"userId"+ channelHandlerContext.channel().id().toString());
        System.out.println("userService="+userService);
        System.out.println(userService.getById(1));
    }


    /**
     * 接受消息
     *  由子类实现
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg)  {
    }

    /**
     * 连接关闭
     * @param channelHandlerContext
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext channelHandlerContext) {
        channelGroupUtil.userRemove(channelHandlerContext.channel());
    }

    /**
     * 异常处理
     * @param channelHandlerContext
     * @param e
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable e) {
        channelGroupUtil.userRemove(channelHandlerContext.channel());
        log.error(e.getMessage(),e);
    }


}
